
package com.trial.area.permission.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.trial.area.common.controller.BaseController;
import com.trial.area.permission.entity.AdminUserVO;
import com.trial.area.permission.entity.PermissionVO;
import com.trial.area.permission.entity.RoleVO;
import com.trial.area.permission.param.RoleParam;
import com.trial.area.permission.param.RolePermissionParam;
import com.trial.area.permission.param.UserRoleParam;
import com.trial.area.permission.service.RolePermissionService;
import com.trial.area.permission.service.RoleService;
import com.trial.area.permission.service.UserRoleService;

/**
 * 角色信息Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class RoleController extends BaseController {
    
    private Logger logger = LoggerFactory.getLogger(RoleController.class);
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;
    
    private final static String LIST_PAGE = "/base/role/role_list";
    
    private final static String ROLE_USER_VIEW_PAGE = "/base/role/role_user_view";
    
    private final static String ROLE_PERMISSION_VIEW_PAGE = "/base/role/role_permission_view";
    
    private final static String UPDATE_PAGE = "/base/role/role_edit";

    private final static String ROLE_USER_LIST_PAGE = "/base/role/role_user_list";

    private final static String ROLE_PERMISSION_LIST_PAGE = "/base/role/role_permission_list";
    
    @RequestMapping(value = "/base/role/toInsert")
    public ModelAndView intoInsert() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        RoleVO roleVO = new RoleVO();
        resultMap.put("roleVO", roleVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }

    @RequestMapping(value = "/base/role/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        RoleVO roleVO = roleService.findById(id);
        resultMap.put("roleVO", roleVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }

    @RequestMapping(value = "/base/role/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(RoleVO roleVO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer affertCount = 0;
            if (StringUtils.isNotBlank(roleVO.getRoleId())) {
                affertCount = roleService.update(roleVO);
            } else {
                roleVO.setRoleId(UUID.randomUUID().toString());
                affertCount = roleService.insert(roleVO);
            }
            if (affertCount != null && affertCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改角色信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改角色信息失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改角色信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改角色信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/base/role/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = roleService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除角色信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除角色信息失败");
            }
        } catch (Exception e) {
            logger.error("删除角色信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除角色信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/base/role/list")
    public ModelAndView queryList(RoleParam roleParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<RoleVO> dataList = roleService.queryByPage(roleParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", roleParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/base/role/permissionView/{id}")
    public ModelAndView viewRolePermission(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        RoleVO roleVO = roleService.findById(id);
        resultMap.put("roleVO", roleVO);
        return new ModelAndView(ROLE_PERMISSION_VIEW_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/base/role/userView/{id}")
    public ModelAndView viewRoleUser(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        RoleVO roleVO = roleService.findById(id);
        resultMap.put("roleVO", roleVO);
        return new ModelAndView(ROLE_USER_VIEW_PAGE, resultMap);
    }

    @RequestMapping(value = "/base/role/insertRoleUser", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String insertRoleUser(String roleId, String adminUserId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (StringUtils.isBlank(roleId)) {
            resultMap.put("result", false);
            resultMap.put("message", "角色ID不能为空");
            return JSONObject.toJSONString(resultMap);
        }

        try {
            String resultMsg = userRoleService.insertRoleUser(roleId, adminUserId);
            if (StringUtils.isBlank(resultMsg)) {
                resultMap.put("result", true);
                resultMap.put("message", "修改角色用户成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", resultMsg);
            }
        } catch (Exception e) {
            logger.error("修改角色用户出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "修改角色用户出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/base/role/insertRolePermission", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String insertRolePermission(String roleId, String permissionId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (StringUtils.isBlank(roleId)) {
            resultMap.put("result", false);
            resultMap.put("message", "角色ID不能为空");
            return JSONObject.toJSONString(resultMap);
        }

        try {
            String resultMsg = rolePermissionService.insertRolePermission(roleId, permissionId);
            if (StringUtils.isBlank(resultMsg)) {
                resultMap.put("result", true);
                resultMap.put("message", "修改角色权限成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", resultMsg);
            }
        } catch (Exception e) {
            logger.error("修改角色权限出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "修改角色权限出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/base/role/deleteRoleUser", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String deleteUserRole(String adminUserId, String roleId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = userRoleService.deleteById(adminUserId, roleId);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除用户角色关系信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除用户角色关系信息失败");
            }
        } catch (Exception e) {
            logger.error("删除用户角色关系信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除用户角色关系信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/base/role/deleteRolePermission", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String deleteRolePermission(String roleId, String permissionId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = rolePermissionService.deleteById(roleId, permissionId);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除角色权限关系信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除角色权限关系信息失败");
            }
        } catch (Exception e) {
            logger.error("删除角色权限关系信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除角色权限关系信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/base/role/roleUserList")
    public ModelAndView queryRoleUserList(UserRoleParam paramMap) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<AdminUserVO> dataList = userRoleService.queryRoleUserList(paramMap);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", paramMap);
        return new ModelAndView(ROLE_USER_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/base/role/rolePermissionList")
    public ModelAndView queryRolePermissionList(RolePermissionParam paramMap) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<PermissionVO> dataList = rolePermissionService.queryRolePermissionList(paramMap);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", paramMap);
        return new ModelAndView(ROLE_PERMISSION_LIST_PAGE, resultMap);
    }

}
